package com.rran.study.chat.server.netty.client;

import com.alibaba.fastjson.JSON;
import com.rran.study.chat.server.dto.request.RegisterMsg;
import com.rran.study.chat.server.dto.request.SingleMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * @author yy
 * @Type WebSocketClient.java
 * @Desc
 * @date 2020/8/6 17:26
 */
public final class WebSocketClientB {

    static final String URL
            = System.getProperty("url",
            "ws://127.0.0.1:9999/websocket");
    static final String SURL
            = System.getProperty("url",
            "wss://127.0.0.1:8443/websocket");

    public static void main(String[] args) throws Exception {
        URI uri = new URI(URL);
        String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final int port = uri.getPort();

        if (!"ws".equalsIgnoreCase(scheme)
                && !"wss".equalsIgnoreCase(scheme)) {
            System.err.println("Only WS(S) is supported.");
            return;
        }
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            final WebSocketClientHandler handler =
                    new WebSocketClientHandler(
                            WebSocketClientHandshakerFactory
                                    .newHandshaker(
                                            uri, WebSocketVersion.V13,
                                            null,
                                            true,
                                            new DefaultHttpHeaders()));

            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(
                                    //http协议为握手必须
                                    new HttpClientCodec(),
                                    new HttpObjectAggregator(8192),
                                    //支持WebSocket数据压缩
                                    WebSocketClientCompressionHandler.INSTANCE,
                                    handler);
                        }
                    });

            //连接服务器
            Channel ch = b.connect(uri.getHost(), port).sync().channel();
            //等待握手完成
            handler.handshakeFuture().sync();

            RegisterMsg registerMsg = new RegisterMsg();
            registerMsg.setBeanId("clientB");
            registerMsg.setMessageUrl("/user/register");
            String registerJson = JSON.toJSONString(registerMsg);
            WebSocketFrame webSocketFrame = new TextWebSocketFrame(registerJson);
            ch.writeAndFlush(webSocketFrame);

            BufferedReader console = new BufferedReader(
                    new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(
                            Unpooled.wrappedBuffer(new byte[]{9, 9, 9, 9}));
                    ch.writeAndFlush(frame);
                } else{
                    SingleMsg singleMsg = new SingleMsg();
                    singleMsg.setContext(msg.toLowerCase());
                    singleMsg.setSource("clientB");
                    singleMsg.setTarget("clientA");
                    singleMsg.setMessageUrl("/chat/single");
                    String userMsg = JSON.toJSONString(singleMsg);
                    WebSocketFrame frame = new TextWebSocketFrame(userMsg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}